/**
 * 
 */
package adc.app.ui.wicket.model;

import java.util.Collections;
import java.util.Iterator;

import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;

import adc.app.spec.IBo;
import adc.app.spec.IBoBs;

public class DomainObjectsDataProvider<T extends IBo> extends SortableDataProvider<T> {
	
	private static final long serialVersionUID = 1L;
	
	private IModel<? extends IBoBs<T>> serviceModel;
	
	public DomainObjectsDataProvider(IModel<? extends IBoBs<T>> serviceModel,
			SortParam defaultSort) {
		super();
		this.serviceModel = serviceModel;
		this.setSort(defaultSort);
	}
	
	public DomainObjectsDataProvider(Class<? extends IBoBs<T>> serviceClass,
			SortParam defaultSort) {
		this(new SpringBeanModel<IBoBs<T>>(serviceClass), defaultSort);
	}
	
	@Override public Iterator<? extends T> iterator(int first, int count) {
		Iterator<T> usersIterator = serviceModel.getObject().list(null,
				first, count, Collections.singletonMap(this.getSort().getProperty(), 
                this.getSort().isAscending())).iterator();
		return usersIterator;
	}

	@Override public IModel<T> model(T object) {
		return new BoModel<T>(object, serviceModel);
	}

	@Override public int size() {
		return (int) serviceModel.getObject().count(null);
	}

	@Override public void detach() {
		serviceModel.detach();
	}
	
}